<template>
  <el-card class="merchant-tree-card">
    <template #header>
      <div class="card-header">
        <span>{{ $t('merchant.name') }}</span>
      </div>
    </template>
    <div class="search-input-wrapper">
      <el-input
          v-model="filterText"
          :placeholder="$t('jbx.text.searchPlaceholder')"
          clearable
      />
    </div>
    <el-tree
        ref="merchantTreeRef"
        :data="merchantTreeData"
        :props="defaultProps"
        node-key="id"
        highlight-current
        :expand-on-click-node="false"
        :filter-node-method="filterNode"
        @node-click="handleNodeClick"
    />
  </el-card>
</template>

<script setup lang="ts">
import {ref, onMounted, watch} from 'vue'
import {listMerchantTree} from '@/api/merchant/merchant'
import {useI18n} from 'vue-i18n'

const {t} = useI18n()

// 定义事件
const emit = defineEmits(['node-click'])

// 树形结构引用
const merchantTreeRef = ref()

// 树形结构数据
const merchantTreeData = ref([])

// 搜索文本
const filterText = ref('')

// 默认属性配置
const defaultProps = {
  children: 'children',
  label: 'merchantName'
}

// 过滤节点
const filterNode = (value: string, data: any) => {
  if (!value) return true
  return data.merchantName.includes(value)
}

// 监听搜索文本变化
watch(filterText, (val) => {
  merchantTreeRef.value.filter(val)
})

// 获取商户列表
function getMerchantList() {
  listMerchantTree({}).then((response: any) => {
    if (response.code === "0") {
      // 构造树形结构数据，添加"全部"根节点
      const merchantList = response.data;
      const treeData = buildTree(merchantList);
      
      merchantTreeData.value = [{
        id: "0",
        merchantName: t('jbx.text.all'),
        children: treeData
      }]
    }
    // else {
    //   // 如果API调用失败，使用模拟数据
    //   useMockData();
    // }
  }).catch((error) => {
    console.error('获取商户列表失败:', error)
    // 出错时设置为空数组而不是使用模拟数据
    merchantTreeData.value = [{
      id: "0",
      merchantName: t('jbx.text.all'),
      children: []
    }]
  })
}

// 构建树形结构
function buildTree(merchantList: any[]) {
  // 创建一个映射来快速查找节点，使用merchantCode作为键
  const nodeMap: Record<string, any> = {};
  const roots: any[] = [];
  
  // 初始化所有节点，使用merchantCode作为映射键
  merchantList.forEach(item => {
    nodeMap[item.merchantCode] = { ...item, children: [] };
  });
  
  // 构建树形结构
  merchantList.forEach(item => {
    const node = nodeMap[item.merchantCode];
    if (!item.parentCode || item.parentCode === '') {
      // 没有父节点的作为根节点
      roots.push(node);
    } else {
      // 有父节点的添加到父节点的children中
      const parent = nodeMap[item.parentCode];
      if (parent) {
        parent.children.push(node);
      } else {
        // 如果找不到父节点，也作为根节点处理
        roots.push(node);
      }
    }
  });
  
  return roots;
}


// 处理节点点击事件
function handleNodeClick(data: any) {
  emit('node-click', data)
}

// 组件挂载时获取数据
onMounted(() => {
  getMerchantList()
})

// 定义暴露给父组件的方法
defineExpose({
  merchantTreeRef
})
</script>

<style scoped>
.merchant-tree-card {
  margin-bottom: 15px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-input-wrapper {
  margin-bottom: 15px;
}
</style>